from flask import render_template,request
from . import admin
import time,random
from app.models import *
import app 


# 首页
@admin.route('/')
def index():
    # 获取所有图书信息
    data = Books.query.all()

    

    # 获取get请求传过来的页数,没有传参数，默认为1
    page = int(request.args.get('page',1))
    paginate = Books.query.filter().paginate(page,5,error_out=False)
    # 获得数据
    data = paginate.items
    # 加载模板
    return render_template("index.html",data=data,paginate=paginate)


# 借出
@admin.route('/jiechu')
def jiechu():
    # 获取所有图书信息
    data = bookBorrow.query.all()    

    # 获取get请求传过来的页数,没有传参数，默认为1
    page = int(request.args.get('page',1))
    paginate = bookBorrow.query.filter().paginate(page,3,error_out=False)
    # 获得数据
    data = paginate.items
    # 加载模板
    return render_template("jiechu.html",data=data,paginate=paginate)


# 添加图书
@admin.route('/book/add')
def bookadd():
    return render_template('bookadd.html')


# 执行添加
@admin.route('/book/insert',methods=['POST'])
def bookinsert():
    # 接受数据
    data = request.form.to_dict()
    print(data)

    # 检测是否有文件上传
    f = request.files.get('image',None)
    if f:
        data['image'] = uploads(f)
    else:
        return '<script>alert("请上传图书封面");location.href="/book/add"</script>'
    # 执行数据添加
    book = Books(**data)
    db.session.add(book)
    db.session.commit()

    # 跳转
    return '<script>alert("录入成功");location.href="/"</script>'

# 封装函数进行文件上传
def uploads(f):
    Suffix = f.filename.split('.').pop()
    filename = str(time.time())+str(random.randint(100,999))+'.'+Suffix
    f.save(app.BASE_DIR+'/static/uploads/'+ filename)
    return '/static/uploads/'+filename




